import { resolve } from 'path'
import { defineConfig, ConfigEnv, UserConfig } from 'vite'
import react from '@vitejs/plugin-react'
import legacy from '@vitejs/plugin-legacy'
// import vitePluginEslint from 'vite-plugin-eslint'
import viteCompression from 'vite-plugin-compression'
import { viteMockServe } from 'vite-plugin-mock'

export default defineConfig((config: ConfigEnv): UserConfig => {
  return {
    resolve: {
      alias: {
        '@': resolve(__dirname, 'src')
      }
    },
    css: {
      preprocessorOptions: {
        // 全局样式引入
        scss: {
          additionalData: '@import "@/styles/variable.scss";',
          javascriptEnabled: true
        }
      }
    },
    server: {
      host: '0.0.0.0', // 服务器主机名，如果允许外部访问，可设置为"0.0.0.0"
      port: 3000,
      open: true,
      hmr: true,
      proxy: {
        '/api': {
          target: 'http://127.0.0.1:8888',
          changeOrigin: true,
          rewrite: path => path.replace(/^\/api/, '')
        }
      }
    },
    build: {
      outDir: 'dist',
      minify: 'terser',
      rollupOptions: {
        output: {
          // Static resource classification and packaging
          chunkFileNames: 'assets/js/[name]-[hash].js',
          entryFileNames: 'assets/js/[name]-[hash].js',
          assetFileNames: 'assets/[ext]/[name]-[hash].[ext]'
        }
      },
      terserOptions: {
        compress: {
          drop_console: config.mode === 'prod',
          drop_debugger: config.mode === 'prod'
        }
      }
    },
    plugins: [
      react(),
      // vitePluginEslint({
      //   // 开发阶段不提示报错
      //   failOnError: false
      // }),
      legacy({
        // 打包代码在传统浏览器or兼容性差的浏览器版本使用
        targets: ['> 0.25%', 'last 2 versions and not dead']
      }),
      viteCompression({
        verbose: true,
        disable: false,
        threshold: 10240, // 体积大于threshold才会被压缩
        algorithm: 'gzip',
        ext: '.gz'
      }),
      viteMockServe({
        mockPath: './src/mock', // 解析
        localEnabled: true, // 开发环境使用
        prodEnabled: false, // 生产环境关闭
        watchFiles: true, // 监听文件内容变化
        injectCode: `
        import { setupProdMockServer } from './mockProdServer';
        setupProdMockServer();
      `
      })
    ]
  }
})
